/*
    Copyright 2007-2008 Adrien Guillon.  All Rights Reserved.

    This file is part of TBB Community Code. 

    TBB Community Code is free software; you can redistribute it
    and/or modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

    TBB Community Code is distributed in the hope that it will be
    useful, but WITHOUT ANY WARRANTY; without even the implied warranty
    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with TBB Community Code; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    As a special exception, you may use this file as part of a free software
    library without restriction.  Specifically, if other files instantiate
    templates or use macros or inline functions from this file, or you compile
    this file and link it with other files to produce an executable, this
    file does not by itself cause the resulting executable to be covered by
    the GNU General Public License.  This exception does not however
    invalidate any other reasons why the executable file might be covered by
    the GNU General Public License.
*/

#ifndef __TCC_ptr_set_H
#define __TCC_ptr_set_H

#include <set>

#include <tbb/spin_mutex.h>

#include <boost/checked_delete.hpp>


namespace tcc {

/**
 * A set that stores pointers to "owned objects."  This container assumes
 * ownership of the pointers it holds, and will call delete on them when this
 * object is destructed, or appopriate member function calls are made.
 *
 * The goal of this class is to provide a method of storing objects in an
 * exception safe manner, without using smart pointers.
 *
 * Instantiate the template with the type of object it will contain, not
 * with pointers itself.
 *
 * The Mutex can be any TBB mutex type, including RW types.
 *
 * The deleter template argument is for a function object which
 * implements void operator()(T* x), and deletes the object.  By
 * default, normal C++ delete is called.
 */

template <typename T, typename Container = typename std::set<T*>, typename Mutex = tbb::spin_mutex, typename Deleter = boost::checked_deleter<T> >
class ptr_set 
{
public:
    typedef Container container_type;
    typedef Mutex mutex_type;


    /**
     * Construct an empty ptr_set 
     */
    ptr_set() { }


    /**
     * The destructor calls delete on all contained object pointers.
     *
     * TODO: Should the destructor use the mutex?
     */
    ~ptr_set()
    {
        if(!empty())
        {
            deleteAll();
        }
    }

    /**
     * Takes ownership of an object.  This container will now own the object,
     * and is responsible for the destruction of the object unless the user
     * destroys it themselves with delete_member(x) or takes ownership of it.
     *
     * This function is thread safe.
     */
    void giveOwnership(T* x)
    {
        { // BEGIN MUTEX
            typename Mutex::scoped_lock lock(_ownedObjectsMutex);
            _ownedObjects.insert(x);
        } // END MUTEX
    }

    /**
     * Take ownership of an object away from this container.  The object
     * will no longer be owned by this container, and a pointer will be
     * returned to the user.
     *
     * This function is thread safe.
     */
    T* takeOwnership(T& x)
    {
        { // BEGIN MUTEX
             typename Mutex::scoped_lock lock(_ownedObjectsMutex);
             _ownedObjects.erase(&x);
        } // END MUTEX

        return &x; 
    }


    /**
     * Call delete on an object owned by this container.  The object deleted
     * is removed from ownership.
     *
     * This function is thread safe.
     */
    void deleteMember(T& x)
    {
        T* objectToDelete;
        objectToDelete = takeOwnership(x);
        _deleter(objectToDelete);
    }

    /**
     * Call delete on all objects owned by this container.  All objects
     * deleted are removed from ownership.  A mutex is used to govern
     * access of internal data structures.  This is the same function which
     * is called by the destructor.
     *
     * This function is thread safe.
     */
    void deleteAll()
    {
        { // BEGIN MUTEX
            
            typename Mutex::scoped_lock lock(_ownedObjectsMutex);

            std::for_each(_ownedObjects.begin(), _ownedObjects.end(), _deleter);

            _ownedObjects.clear();

        } // END MUTEX
    }

    /**
     * Check if this container owns anything.
     *
     * This function is thread safe.
     *
     * @return true if there are no objects owned, false otherwise.
     */
    bool empty() const
    {
        return _ownedObjects.empty();
    }


    /**
     * Swaps the contents of this ptr_set with a ptr_set instance
     * provided as an argument.
     *
     * This function is thread safe, however it requires two mutexes,
     * one for this ptr_set and one for the ptr_set argument.
     */
    void swap(ptr_set& x)
    {
        { // BEGIN MUTEX ON x
            typename Mutex::scoped_lock lock_x(x._ownedObjectsMutex);

            { // BEGIN MUTEX ON this
                typename Mutex::scoped_lock lock_this(_ownedObjectsMutex);

                _ownedObjects.swap(x);
                
            }

        }
    }

private:

    /**
     * Actual object container.
     */
    Container _ownedObjects;

    /**
     * Copying a ptr_set is forbidden in case the user accidently
     * does so.  If copying a ptr_set were permitted, the contents
     * of the rvalue would have to be cleared, which might not be
     * what the user expected.  Instead, the user must call the function
     * swap(). 
     */
    ptr_set(const ptr_set& x);

    /**
     * Make assignment illegal.  Users should use swap() only.
     */
    ptr_set& operator(const ptr_set&);

    /**
     * Instantiate an actual instance of the deleter.
     */
    Deleter _deleter;
    
    /**
     * Mutex for the internal data structure.
     */
    Mutex _ownedObjectsMutex;
};

} // END NAMESPACE tcc

#endif

